package cn.demoxy.listener;

import cn.demoxy.mapper.DemoUserMapper;
import cn.demoxy.mapper.DemoUserRoleMapper;
import cn.demoxy.model.entity.DemoUser;
import cn.demoxy.model.entity.DemoUserRole;
import cn.demoxy.model.vo.DemoUserVO;
import cn.demoxy.service.IDemoUserService;
import cn.demoxy.utils.SaltUtils;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;

/**
 * @auther demo
 * @date 2022/5/23 9:56
 * excel用户导入数据库监听器
 */
@AllArgsConstructor
public class UserListener extends AnalysisEventListener<DemoUserVO> {

    private DemoUserMapper userMapper;

    private DemoUserRoleMapper userRoleMapper;

    private final String INIT_PASSWORD = "123456";

    @Override
    public void invoke(DemoUserVO demoUserVO, AnalysisContext analysisContext) {
        //调用方法添加数据库
        DemoUser user = new DemoUser();
        BeanUtils.copyProperties(demoUserVO, user);
        user.setPassword(INIT_PASSWORD);
        //生成随机盐
        String salt = SaltUtils.getSalt(8);
        //将随机盐保存到数据
        user.setSalt(salt);
        //设置为已激活
        user.setEnableFlag("0");
        //明文密码进行md5 + salt + hash散列加密
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());
        if (userMapper.selectOne(new QueryWrapper<DemoUser>().eq("username", demoUserVO.getUsername())) == null) {
            userMapper.insert(user);
        }
//        user.getRoleIds().forEach(roleId -> {
//            userRoleMapper.insert(new DemoUserRole().setUserId(user.getId()).setRoleId(roleId));
//        });
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
